package com.jk.myimkit.imkit.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jk.myimkit.R;
import com.jk.myimkit.imkit.RongBaseActivity;
import com.jk.myimkit.imkit.RongContext;
import com.jk.myimkit.imkit.RongIM;
import com.jk.myimkit.imkit.model.Event;
import com.jk.myimkit.imkit.tools.RongWebviewActivity;
import com.jk.myimkit.imkit.utilities.PermissionCheckUtil;
import com.jk.myimkit.imkit.utils.FileTypeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.message.FileMessage;

public class FilePreviewActivity extends RongBaseActivity implements View.OnClickListener {
    private static final int NOT_DOWNLOAD = 0;
    private static final int DOWNLOADED = 1;
    private static final int DOWNLOADING = 2;
    private static final int DELETED = 3;
    private static final int DOWNLOAD_ERROR = 4;
    private static final int DOWNLOAD_CANCEL = 5;
    private static final int DOWNLOAD_SUCCESS = 6;
    private static final int ON_SUCCESS_CALLBACK = 100;
    private static final int ON_PROGRESS_CALLBACK = 101;
    private static final int ON_CANCEL_CALLBACK = 102;
    private static final int ON_ERROR_CALLBACK = 103;
    public static final int REQUEST_CODE_PERMISSION = 104;
    private static final String TXT_FILE = ".txt";
    private static final String APK_FILE = ".apk";
    private ImageView mFileTypeImage;
    private TextView mFileNameView;
    private TextView mFileSizeView;
    private Button mFileButton;
    private ProgressBar mFileDownloadProgressBar;
    private LinearLayout mDownloadProgressView;
    protected TextView mDownloadProgressTextView;
    protected View mCancel;
    private FilePreviewActivity.FileDownloadInfo mFileDownloadInfo;
    protected FileMessage mFileMessage;
    private Message mMessage;
    private int mProgress;
    private String mFileName;
    private long mFileSize;
    private List<Toast> mToasts;
    private FrameLayout contentContainer;

    public FilePreviewActivity() {
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.rc_ac_file_download);
        this.mFileMessage = (FileMessage)this.getIntent().getParcelableExtra("FileMessage");
        this.mMessage = (Message)this.getIntent().getParcelableExtra("Message");
        this.mProgress = this.getIntent().getIntExtra("Progress", 0);
        this.initView();
        this.initData();
        this.getFileDownloadInfo();
    }

    public void setContentView(int resId) {
        this.contentContainer.removeAllViews();
        View view = LayoutInflater.from(this).inflate(resId, (ViewGroup)null);
        this.contentContainer.addView(view);
    }

    private void initData() {
        this.mToasts = new ArrayList();
        this.mFileName = this.mFileMessage.getName();
        this.mFileTypeImage.setImageResource(FileTypeUtils.fileTypeImageId(this.mFileName));
        this.mFileNameView.setText(this.mFileName);
        this.mFileSize = this.mFileMessage.getSize();
        this.mFileSizeView.setText(FileTypeUtils.formatFileSize(this.mFileSize));
        this.mFileDownloadInfo = new FilePreviewActivity.FileDownloadInfo();
        this.mFileButton.setOnClickListener(this);
        this.mCancel.setOnClickListener(this);
        RongContext.getInstance().getEventBus().register(this);
    }

    private void initView() {
        this.contentContainer = (FrameLayout)this.findViewById(R.id.rc_ac_ll_content_container);
        View view = LayoutInflater.from(this).inflate(R.layout.rc_ac_file_preview_content, (ViewGroup)null);
        this.contentContainer.addView(view);
        this.mFileTypeImage = (ImageView)this.findViewById(R.id.rc_ac_iv_file_type_image);
        this.mFileNameView = (TextView)this.findViewById(R.id.rc_ac_tv_file_name);
        this.mFileSizeView = (TextView)this.findViewById(R.id.rc_ac_tv_file_size);
        this.mFileButton = (Button)this.findViewById(R.id.rc_ac_btn_download_button);
        this.mDownloadProgressView = (LinearLayout)this.findViewById(R.id.rc_ac_ll_progress_view);
        this.mCancel = this.findViewById(R.id.rc_btn_cancel);
        this.mFileDownloadProgressBar = (ProgressBar)this.findViewById(R.id.rc_ac_pb_download_progress);
        this.mDownloadProgressTextView = (TextView)this.findViewById(R.id.rc_ac_tv_download_progress);
        TextView title = (TextView)this.findViewById(R.id.rc_action_bar_title);
        title.setText(R.string.rc_ac_file_download_preview);
        if (this.mMessage.getMessageDirection() == Message.MessageDirection.RECEIVE) {
            if (this.mProgress == 0) {
                this.mDownloadProgressView.setVisibility(View.GONE);
                this.mFileButton.setVisibility(View.VISIBLE);
            } else if (this.mProgress == 100) {
                this.mDownloadProgressView.setVisibility(View.GONE);
                this.mFileButton.setVisibility(View.VISIBLE);
            } else {
                this.mFileButton.setVisibility(View.GONE);
                this.mDownloadProgressView.setVisibility(View.VISIBLE);
                this.mFileDownloadProgressBar.setProgress(this.mProgress);
            }
        }

        this.onCreateActionbar(new FilePreviewActivity.ActionBar());
    }

    public void onClick(View v) {
        if (v == this.mFileButton) {
            switch(this.mFileDownloadInfo.state) {
                case 0:
                case 3:
                case 4:
                case 5:
                    this.downloadFile();
                    break;
                case 1:
                case 6:
                    Uri uri = this.mFileMessage.getLocalPath();
                    String path = uri.toString();
                    if (path.toLowerCase().startsWith("file://")) {
                        path = path.substring(7);
                    }

                    this.openFile(this.mFileName, path);
                case 2:
            }
        } else if (v == this.mCancel && this.mFileDownloadInfo.state != 5) {
            this.mFileDownloadInfo.state = 5;
            this.refreshDownloadState();
            RongIM.getInstance().cancelDownloadMediaMessage(this.mMessage, (RongIMClient.OperationCallback)null);
        }

    }

    public void openFile(String fileName, String fileSavePath) {
        if (!this.openInsidePreview(fileSavePath)) {
            Intent intent = FileTypeUtils.getOpenFileIntent(fileName, fileSavePath);

            try {
                if (intent != null) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    this.startActivity(intent);
                } else {
                    Toast.makeText(this, this.getString(R.string.rc_ac_file_preview_can_not_open_file), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception var5) {
                Toast.makeText(this, this.getString(R.string.rc_ac_file_preview_can_not_open_file), Toast.LENGTH_SHORT).show();
            }
        }

    }

    protected boolean openInsidePreview(String fileSavePath) {
        if (fileSavePath.endsWith(".txt")) {
            Intent webIntent = new Intent(this, RongWebviewActivity.class);
            webIntent.setPackage(this.getPackageName());
            webIntent.putExtra("url", "file://" + fileSavePath);
            this.startActivity(webIntent);
            return true;
        } else if (fileSavePath.endsWith(".apk")) {
            File file = new File(fileSavePath);
            Intent installIntent = new Intent("android.intent.action.VIEW");
            installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            installIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            this.startActivity(installIntent);
            return true;
        } else {
            return false;
        }
    }

    @TargetApi(23)
    private void downloadFile() {
        String[] permission = new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"};
        if (!PermissionCheckUtil.checkPermissions(this, permission)) {
            PermissionCheckUtil.requestPermissions(this, permission, 104);
        } else {
            this.mFileButton.setVisibility(View.GONE);
            this.mDownloadProgressView.setVisibility(View.VISIBLE);
            this.mFileDownloadInfo.state = 2;
            this.mDownloadProgressTextView.setText(this.getString(R.string.rc_ac_file_download_progress_tv, new Object[]{FileTypeUtils.formatFileSize(0L), FileTypeUtils.formatFileSize(this.mFileSize)}));
            RongIM.getInstance().downloadMediaMessage(this.mMessage, (IRongCallback.IDownloadMediaMessageCallback)null);
        }
    }

    private void getFileDownloadInfo() {
        if (this.mFileMessage.getLocalPath() != null) {
            String path = this.mFileMessage.getLocalPath().getPath();
            if (path != null) {
                File file = new File(path);
                if (file.exists()) {
                    this.mFileDownloadInfo.state = 1;
                } else {
                    this.mFileDownloadInfo.state = 3;
                }
            }
        } else if (this.mProgress > 0 && this.mProgress < 100) {
            this.mFileDownloadInfo.state = 2;
            this.mFileDownloadInfo.progress = this.mProgress;
        } else {
            this.mFileDownloadInfo.state = 0;
        }

        this.refreshDownloadState();
    }

    private void refreshDownloadState() {
        switch(this.mFileDownloadInfo.state) {
            case 0:
                this.mFileButton.setText(this.getString(R.string.rc_ac_file_preview_begin_download));
                break;
            case 1:
                this.mFileButton.setText(this.getString(R.string.rc_ac_file_download_open_file_btn));
                break;
            case 2:
                this.mFileButton.setVisibility(View.GONE);
                this.mDownloadProgressView.setVisibility(View.VISIBLE);
                this.mFileDownloadProgressBar.setProgress(this.mFileDownloadInfo.progress);
                long downloadedFileLength = (long)((double)this.mFileMessage.getSize() * ((double)this.mFileDownloadInfo.progress / 100.0D) + 0.5D);
                this.mDownloadProgressTextView.setText(this.getString(R.string.rc_ac_file_download_progress_tv, new Object[]{FileTypeUtils.formatFileSize(downloadedFileLength), FileTypeUtils.formatFileSize(this.mFileSize)}));
                break;
            case 3:
                this.mFileButton.setText(this.getString(R.string.rc_ac_file_preview_begin_download));
                break;
            case 4:
                this.mDownloadProgressView.setVisibility(View.GONE);
                this.mFileButton.setVisibility(View.VISIBLE);
                this.mFileButton.setText(this.getString(R.string.rc_ac_file_preview_begin_download));
                Toast toast = Toast.makeText(this, this.getString(R.string.rc_ac_file_preview_download_error), Toast.LENGTH_SHORT);
                if (this.mFileDownloadInfo.state != 5) {
                    toast.show();
                }

                this.mToasts.add(toast);
                break;
            case 5:
                this.mDownloadProgressView.setVisibility(View.GONE);
                this.mFileDownloadProgressBar.setProgress(0);
                this.mFileButton.setVisibility(View.VISIBLE);
                Toast.makeText(this, this.getString(R.string.rc_ac_file_preview_download_cancel), Toast.LENGTH_SHORT).show();
                break;
            case 6:
                this.mDownloadProgressView.setVisibility(View.GONE);
                this.mFileButton.setVisibility(View.VISIBLE);
                this.mFileButton.setText(this.getString(R.string.rc_ac_file_download_open_file_btn));
                Toast.makeText(this, this.getString(R.string.rc_ac_file_preview_downloaded) + this.mFileDownloadInfo.path, Toast.LENGTH_SHORT).show();
        }

    }

    public void onEventMainThread(Event.FileMessageEvent event) {
        if (this.mMessage.getMessageId() == event.getMessage().getMessageId()) {
            switch(event.getCallBackType()) {
                case 100:
                    if (this.mFileDownloadInfo.state != 5) {
                        if (event.getMessage() == null || event.getMessage().getContent() == null) {
                            return;
                        }

                        FileMessage fileMessage = (FileMessage)event.getMessage().getContent();
                        this.mFileMessage.setLocalPath(Uri.parse(fileMessage.getLocalPath().toString()));
                        this.mFileDownloadInfo.state = 6;
                        this.mFileDownloadInfo.path = fileMessage.getLocalPath().toString();
                        this.refreshDownloadState();
                    }
                    break;
                case 101:
                    if (this.mFileDownloadInfo.state != 5) {
                        this.mFileDownloadInfo.state = 2;
                        this.mFileDownloadInfo.progress = event.getProgress();
                        this.refreshDownloadState();
                    }
                case 102:
                default:
                    break;
                case 103:
                    if (this.mFileDownloadInfo.state != 5) {
                        this.mFileDownloadInfo.state = 4;
                        this.refreshDownloadState();
                    }
            }
        }

    }

    protected void onCreateActionbar(FilePreviewActivity.ActionBar actionBar) {
    }

    protected void onResume() {
        super.onResume();
        this.getFileDownloadInfo();
    }

    protected void onStop() {
        super.onStop();
    }

    protected void onDestroy() {
        RongContext.getInstance().getEventBus().unregister(this);

        try {
            Iterator var1 = this.mToasts.iterator();

            while(var1.hasNext()) {
                Toast toast = (Toast)var1.next();
                toast.cancel();
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        super.onDestroy();
    }

    class FileDownloadInfo {
        int state;
        int progress;
        String path;

        FileDownloadInfo() {
        }
    }

    public class ActionBar {
        public ActionBar() {
        }

        public View setActionBar(int res) {
            FilePreviewActivity.this.titleContainer.removeAllViews();
            FilePreviewActivity.this.titleContainer.setBackgroundColor(0);
            return LayoutInflater.from(FilePreviewActivity.this).inflate(res, FilePreviewActivity.this.titleContainer);
        }
    }
}
